package com.banciyuan.bcywebview.biz.main.mainpage.maincircle;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoreApi;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.circles.discover.DiscoverCircleActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleSmoothActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.CircleTagSmoothActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.CommonUtils;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.CircleEnterStatistics;
import de.greenrobot.daoexample.model.FollowTag;

/**
 * Created by hy on 2015/12/2.
 */
public class MainCircleFragment extends BaseLazyContainerFragment implements View.OnClickListener {

    private RequestQueue mQueue;

    private LinearLayout other_work_container;
    private LinearLayout other_tag_container;
    private View mProgressbarView;
    private ProgressbarHelper mProgressbarHelper;

    private ScrollView scrollView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = View.inflate(getActivity(), R.layout.maincircle_layout, null);
        initArgs();
        initProgressbar(rootview);
        initUi(rootview);
        initAction();
        return rootview;
    }

    @Override
    public void fetchData() {
        initData();
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();

            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    public void selfUpdateData() {
        scrollView.smoothScrollTo(0, 0);
    }

    @Override
    protected void initUi(View rootview) {
        scrollView = (ScrollView) rootview.findViewById(R.id.refresh_container);
        other_work_container = (LinearLayout) rootview.findViewById(R.id.others_work_container);
        other_tag_container = (LinearLayout) rootview.findViewById(R.id.others_tag_container);
        rootview.findViewById(R.id.focus_interest).setOnClickListener(this);
        rootview.findViewById(R.id.tag_interest).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        getDiscoverTag();
        getPopTags();
    }

    private void formatWork(List<CircleEnterStatistics> templist) {
        for (CircleEnterStatistics c : templist) {
            c.setName(c.getReal_name());
            c.setType("work");
        }
    }

    private void getDiscoverTag() {
        String url = HttpUtils.BASE_URL + TagApi.getHotSubFollow();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    JSONObject jsonObject = new JSONObject(response);
                    List<FollowTag> flist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<FollowTag>>() {
                    }.getType());
                    renderDiscoverTag(flist);
                    onSucc();
                } catch (Exception e) {
                    onSucc();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onSucc();
            }
        };
        Map<String, String> map = HttpUtils.getData(pairs);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    private void renderDiscoverTag(List<FollowTag> flist) {
        other_tag_container.removeAllViews();
        int line = flist.size() % 4 == 0 ? flist.size() / 4 : flist.size() / 4 + 1;
        for (int i = 0; i < line; i++) {
            LinearLayout ll = new LinearLayout(getActivity());
            ll.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < 4; j++) {
                int index = j + (i * 4);
                LinearLayout.LayoutParams llchild = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                llchild.weight = 1;
                llchild.bottomMargin = UIUtils.dip2px(16, getActivity());
                LinearLayout itemView = (LinearLayout) View.inflate(getActivity(), R.layout.local_circle_item, null);
                itemView.setGravity(Gravity.CENTER);
                itemView.setLayoutParams(llchild);
                if (index < flist.size()) {
                    itemView.setVisibility(View.VISIBLE);
                    final FollowTag c = flist.get(index);
                    TextView tv = (TextView) itemView.findViewById(R.id.tv_work);
                    ImageView iv = (ImageView) itemView.findViewById(R.id.iv_work);
                    tv.setMaxWidth(CommonUtils.getWidthPixels(getActivity()) / 4 - UIUtils.dip2px(16, getActivity()));
                    tv.setText(c.getTag_name());
                    ImageLoader.getInstance().displayImage(c.getCover(), iv, ImageOptions.options);
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent();
                            intent.putExtra(gotoUtil.INTENT_VALUE_ONE, c.getTag_name());
                            intent.putExtra("from", 1);
                            intent.setClass(getActivity(), CircleTagSmoothActivity.class);
                            startActivity(intent);
                        }
                    });
                } else {
                    itemView.setVisibility(View.INVISIBLE);
                }
                ll.addView(itemView);
            }
            other_tag_container.addView(ll);
        }
    }

    private void getPopTags() {
        String url = HttpUtils.BASE_URL + CoreApi.getworkHotWork();
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    JSONObject jsonObject = new JSONObject(response);
                    List<CircleEnterStatistics> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<CircleEnterStatistics>>() {
                    }.getType());
                    formatWork(templist);
                    renderOther(templist);
                } catch (Exception e) {
                    onSucc();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onSucc();
            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, null, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

    private void renderOther(List<CircleEnterStatistics> clist) {
        setLocalCircleUi(clist, other_work_container);
        onSucc();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_order_acg:
            case R.id.footer_goacg:
                gotoUtil.gotoAct(getActivity(), DiscoverCircleActivity.class, DiscoverCircleActivity.TYPE_WORK);
                break;
            case R.id.focus_interest:
                gotoUtil.gotoAct(getActivity(), DiscoverCircleActivity.class, DiscoverCircleActivity.TYPE_WORK);
                break;
            case R.id.tag_interest:
                gotoUtil.gotoAct(getActivity(), DiscoverCircleActivity.class, DiscoverCircleActivity.TYPE_TAG);
                break;
        }
    }


    private void setLocalCircleUi(List<CircleEnterStatistics> clist, LinearLayout linearLayout) {
        linearLayout.removeAllViews();
        if (clist.size() > 20) {
            clist = clist.subList(0, 20);
        }
        int line = clist.size() % 4 == 0 ? clist.size() / 4 : clist.size() / 4 + 1;
        for (int i = 0; i < line; i++) {
            LinearLayout ll = new LinearLayout(getActivity());
            ll.setOrientation(LinearLayout.HORIZONTAL);
            for (int j = 0; j < 4; j++) {
                int index = j + (i * 4);
                LinearLayout.LayoutParams llchild = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                llchild.weight = 1;
                llchild.bottomMargin = UIUtils.dip2px(16, getActivity());
                LinearLayout itemView = (LinearLayout) View.inflate(getActivity(), R.layout.local_circle_item, null);
                itemView.setGravity(Gravity.CENTER);
                itemView.setLayoutParams(llchild);
                if (index < clist.size()) {
                    itemView.setVisibility(View.VISIBLE);
                    final CircleEnterStatistics c = clist.get(index);
                    TextView tv = (TextView) itemView.findViewById(R.id.tv_work);
                    ImageView iv = (ImageView) itemView.findViewById(R.id.iv_work);
                    tv.setMaxWidth(CommonUtils.getWidthPixels(getActivity()) / 4 - UIUtils.dip2px(16, getActivity()));
                    tv.setText(c.getName());
                    ImageLoader.getInstance().displayImage(c.getCover(), iv, ImageOptions.options);
                    itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (c.getType().equals("work")) {
                                Intent intent = new Intent();
                                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, c.getId());
                                intent.putExtra("from", 1);
                                intent.setClass(getActivity(), CircleSmoothActivity.class);
                                startActivity(intent);
                            } else if (c.getType().equals("tag")) {
                                Intent intent = new Intent();
                                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, c.getName());
                                intent.putExtra("from", 1);
                                intent.setClass(getActivity(), CircleTagSmoothActivity.class);
                                startActivity(intent);
                            }
                        }
                    });
                } else {
                    itemView.setVisibility(View.INVISIBLE);
                }
                ll.addView(itemView);
            }
            linearLayout.addView(ll);
        }
    }

    private void onSucc() {
        mProgressbarHelper.onSuccess();
    }
}
